﻿// See https://aka.ms/new-console-template for more information
using static System.Console;

Title = "C#中如何使用Yield关键字";



List<int> nums = new List<int>();

//for (int i = 0; i <= 10; i++)
//{
//    if (i % 2 == 0)
//    {
//        nums.Add(i);
//    }
//}


//foreach (var i in nums)
//{
//    WriteLine(i);
//}



//IEnumerable<int> arr = GetNums();
//foreach(var item in arr)
//{
//    WriteLine(item);
//}




IEnumerator<int> arr = GetEnumerator();
//WriteLine(arr.Current);
arr.MoveNext();
WriteLine(arr.Current);

arr.MoveNext();
WriteLine(arr.Current);


ReadKey();

IEnumerator<int> GetEnumerator()
{
    int i = 1;
    while (true)
    {
        yield return i++;
    }

}


IEnumerable<int> GetNums()
{
    for (int i = 0; i <= 10; i++)
    {
        if (i == 5)
        {
            yield break;
        }
        if (i % 2 == 0)
        {
            yield return i;
        }
    }
}